package system.util.message;

import java.io.Serializable;

/**
 * Message of inter agent communications 
 */
public class Message implements Serializable {
	private static final long serialVersionUID = 2177183933013826533L;
	/**
	 * Separator of keywords
	 */
	public static final String SEPARATOR = "##";
	/**
	 * String table containing the list of keywords (ex : BUY 3 TOMATES)
	 */
	private String[] message;
	/**
	 * Name of the sender of the message
	 */
	private String senderName;
	/**
	 * Data contained in the message
	 */
	private Object data;
	/**
	 * Unique Id of the message
	 */
	private int id;
	/**
	 * Id of the next message
	 */
	private static int nextId = 0;
	/**
	 * Semaphore which synchronize the creation of new message with a unique ID
	 */
	private static final Object synchro = new Object();
	
	/**
	 * Simple constructor with a table of keyWords
	 */
	public Message(String senderName, String[] message){
		this(senderName);
		this.message = message;
	}
	
	/**
	 * Constructor which parse a String to extracts the keywords (thanks to Message.SEPARATOR)
	 */
	public Message(String senderName, String message) {
		this(senderName);
		if (message != null) {
			this.message = message.split(Message.SEPARATOR);
		}
		else {
			this.message = null;
		}
			
	}
	
	private Message(String senderName) {
		this.id = this.getNextId();
		this.senderName = senderName;
	}
	
	private int getNextId() {
		synchronized (synchro) {
			return Message.nextId++;
		}
	}
	
	public String[] getMessage() {
		return message;
	}

	public void setMessage(String[] message) {
		this.message = message;
	}

	public String getSenderName() {
		return senderName;
	}

	public void setSenderName(String senderName) {
		this.senderName = senderName;
	}

	public int getId() {
		return id;
	}
	
	public void setData(Object data){
		this.data = data;
	}
	
	public Object getData(){
		return data;
	}
}
